import * as React from "react";
import { usePageEvent } from "remax/macro";
import {
  getStorageSync,
  getUserProfile,
  navigateTo,
  request,
  setStorageSync,
  View,
} from "remax/wechat";
import { Button, Card, SearchBar, Skeleton, Tabs } from "annar";
import { VideoCategory } from "@/type/category";
import { origin } from "@/config/config";
import { Video } from "@/type/video";
import { LongScrollView } from "@/component/long-scroll-view";
import Tabbar from "@vant/weapp/lib/tabbar";
import TabbarItem from "@vant/weapp/lib/tabbar-item";

const { TabContent } = Tabs;
let hotVideoList: Video[] = [];

export const wxLogin = () => {
  wx.login({
    success(res) {
      if (res.code) {
        //发起网络请求
        let code = res.code;
        wx.request({
          url: `${origin}/login`,
          header: {
            "Content-Type": "application/x-www-form-urlencoded",
            Accept: "application/json",
          },
          method: "POST",
          dataType: "json",
          data: {
            code: "" + code,
          },
          success: (res: any) => {
            let loginInfo = res.data.data;
            // login info 写入内存
            setStorageSync("loginInfo", loginInfo);
          },
        });
      } else {
        console.log("登录失败！" + res.errMsg);
      }
    },
  });
};

export default () => {
  const [active, setActive] = React.useState(0);
  const [stateKey, setStateKey] = React.useState("recommended");
  const [tabList, setTabList] = React.useState<VideoCategory[]>([]);
  const [videoList, setVideoList] = React.useState<Video[]>([]);
  const [loading, setLoading] = React.useState(true);

  usePageEvent("onLoad", () => {
    request({
      url: `${origin}/category/getCategoryList`,
      success: (res) => {
        if (res.data.code === 200 && res.data.data !== []) {
          let categoryList = res.data.data;
          if (
            categoryList === null ||
            categoryList === [] ||
            categoryList === undefined
          ) {
            categoryList = [
              {
                id: 0,
                label: "recommended",
                name: "推荐",
              },
            ];
          } else {
            categoryList.unshift({
              id: 0,
              label: "recommended",
              name: "推荐",
            });
          }

          setTabList(categoryList);
          if (res.data.code === 200 && res.data.data !== []) {
            request({
              url: `${origin}/video/hotVideoList/1/100`,
              success: (res) => {
                hotVideoList = res.data.data;

                setVideoList(hotVideoList);
                setLoading(false);

                // 登录
                wxLogin();
              },
            });
          } else {
            console.log("fail to get hot video list");
          }
        } else {
          console.log("fail to get category list");
        }
      },
    });
  });

  const handlerTabClick = (i: { key: string; tab: string }) => {
    setStateKey(i.key);
    if (i.key === "recommended") {
      setVideoList(hotVideoList);
    } else {
      request({
        method: "GET",
        url: `${origin}/video/videoList/1/2?categoryLabel=${i.key}`,
        success: (res) => {
          setVideoList(res.data.data.rows);
        },
      });
    }
  };

  const onChange = (event: any) => {
    let userInfo: WechatMiniprogram.UserInfo = {
      avatarUrl: "",
      city: "",
      country: "",
      gender: 0,
      language: "en",
      nickName: "",
      province: "",
    };
    if (event.detail === 2) {
      getUserProfile({
        desc: "用于完善用户资料",
        success: (res) => {
          userInfo = res.userInfo;
        },
        complete: () => {
          console.log(userInfo);
          if (userInfo.nickName !== "") {
            setStorageSync("userInfo", userInfo);
            navigateTo({
              url: `/pages/user/index`,
            });
          }
        },
      });
    } else if (event.detail === 1) {
      navigateTo({
        url: `/pages/upload/index`,
      });
    } else {
      setActive(event.detail);
    }
  };

  const loadingMore = () => {
    console.log(stateKey);
    if (stateKey === "recommended") {
      // let pageSize = 2
      // if (hotVideoList.length < 1) return ;
      // let page = Math.floor((hotVideoList.length - 1)/ pageSize) + 1 + 1
      // request({
      //   url: `${origin}/video/hotVideoList/${page}/${pageSize}`,
      //   success: (res) => {
      //     let tempList = hotVideoList
      //     tempList = tempList.concat(res.data.data.rows)
      //     setVideoList(tempList)
      //   }
      // })
    } else {
      let pageSize = 2;
      let page = Math.floor((videoList.length - 1) / pageSize) + 1 + 1;
      console.log(videoList.length / pageSize);
      let loginInfo = getStorageSync("loginInfo");
      request({
        method: "GET",
        url: `${origin}/video/videoList/${page}/${pageSize}?categoryLabel=${stateKey}`,
        header: {
          token: loginInfo.token,
          "Content-Type": "application/x-www-form-urlencoded",
          Accept: "application/json",
        },
        success: (res) => {
          let tempList = videoList;
          tempList = tempList.concat(res.data.data.rows);
          console.log(tempList);
          setVideoList(tempList);
        },
      });
    }
  };

  return (
    <Skeleton fade image title repetitions={3} loading={loading}>
      <View>
        <SearchBar
          style={{ margin: "0 10px" }}
          placeholder="搜索"
          onFocus={() => {
            navigateTo({
              url: "/pages/search/index",
            });
          }}
        />
        <Tabs type="plain" onTabClick={handlerTabClick} activeKey={stateKey}>
          {tabList.map((tab) => (
            <TabContent key={tab.label} tab={tab.name}>
              <Card>
                <LongScrollView
                  data={videoList}
                  onScrollToLower={loadingMore}
                />
              </Card>
            </TabContent>
          ))}
        </Tabs>

        <Tabbar active={active} bindchange={onChange}>
          <TabbarItem icon="wap-home">首页</TabbarItem>
          <TabbarItem icon={"plus"}>上传</TabbarItem>
          <TabbarItem icon="manager">我的</TabbarItem>
        </Tabbar>
      </View>
    </Skeleton>
  );
};
